package com.xym.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xym.common.util.CookieUtils;
import com.xym.pojo.User;
import com.xym.pojo.UserThreadLocal;
import com.xym.web.Service.UserService;

public class LoginInterceptor implements HandlerInterceptor{

	@Autowired
	private UserService userService;
	
	public static final String COOKIE_NAME="TT_TOKEN";
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 获取用户的Token
        String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if(StringUtils.isEmpty(token)){
        	 // 如果没有token，证明未登录,跳转到登录页
            response.sendRedirect(userService.SSO_TAOTAO_BASE_URL + "/user/login.html");
            return false;
        }
        // 从SSO获取用户信息
        User user = this.userService.queryUserByToken(token);
        if (user == null) {
            // 没有用户，说明登录超时，跳转到登录页面
            response.sendRedirect(userService.SSO_TAOTAO_BASE_URL + "/user/login.html");
            return false;
        }
        //此处的User对象传给OrderController
        UserThreadLocal.set(user);
        return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//在完成方法中擦出User对象
		UserThreadLocal.set(null);
		
	}

}
